import time
from django.test import TestCase
import pandas as pd
from openpyxl import load_workbook
from .yida_config import YidaClient
import unittest

admin_user_id = "171537110136635590"

class YidaTest(TestCase):
    def setUp(self) -> None:
        return super().setUp()
    

    def test_delete_in_xlsx(self):
        print("开始删除委托")
        workbook = load_workbook('/Users/xusijiao/Desktop/xiaming_py/reportservice/yida_app_service/zhongji/resource/委托录入_20240818063734.xlsx')
        sheet = workbook.active
        # 打印每一行的数据
        for index,row in enumerate(sheet.iter_rows(values_only=True)):
            print(f"正在处理第{index-1}条数据")
            yida_client = YidaClient()
            res = yida_client.delete_form_data(row[0],admin_user_id)
        print("删除完成")
            
    def test_import_contract(self):
        print("开始导入委托")
        # return
        workbook = load_workbook('/Users/xusijiao/Desktop/xiaming_py/reportservice/yida_app_service/zhongji/resource/未完成.xlsx')
        sheet = workbook.active
        # 打印每一行的数据
        for index,row in enumerate(sheet.iter_rows(values_only=True)):
            # if index < 576:
            #     continue
            if index < 1:
                continue
            # if index > 1617:
            #     break
            print(f"正在处理第{index-2}条数据，委托编号为：{row[0]}")
            yida_client = YidaClient()
            result = yida_client.get_form_data_by_search_field(
                form_uuid='FORM-1D5C1966CFD0460593F327A59C7F35B77NAC',
                userId=admin_user_id,
                search_field=[
                    {
                      "type": "TEXT",
                      "operator": "eq",
                      "componentName": "TextField",
                      "key": "textField_lyy3v0sa",
                      "value": row[9]
                    }
                  ]
            )
            if not result:
                print(f"未找到工程编号为{row[9]}的记录")
                with open('/Users/xusijiao/Desktop/xiaming_py/reportservice/yida_app_service/zhongji/resource/fail.txt', 'a', encoding='utf-8') as file:
                # 在文件末尾写入内容
                    file.write(f"未找到工程编号为{row[9]}的记录\n")
                continue
            form_inst_id = result[0].form_instance_id
            form_data = result[0].form_data

            area_map = {
                "台州":"F",
                "金华":"I",
                "其它":"Y",
                "衢州":"J",
                "杭州":"A",
                "丽水":"H",
                "安徽":"Z",
                "绍兴":"E",
                "嘉兴":"C",
                "温州":"G",
                "湖州":"B",
                "宁波、舟山":"D",
            }
            commission_info = {
                "associationFormField_lqqbd27d":[
                  {
                    "appType": 'APP_G6DTJQRQOH9QKN3CF4EQ', 
                    "formType": 'receipt',
                    "formUuid": 'FORM-1D5C1966CFD0460593F327A59C7F35B77NAC',
                    "instanceId": form_inst_id,
                    "title": form_data["textField_lyy3v0sa"],
                    "subTitle": form_data["textField_logmivk3"],
                  },  
                ],
                "selectField_lyy3k19t":"-",
                "radioField_lz2agi63":"否",
                "employeeField_lyxzlrkg":[admin_user_id],
                "selectField_lyy3k19m":"-",
                "textField_lqqbd279":row[0], # 委托编号
                "textField_lqqbd27b":row[1], # 报告编号
                "textField_lqqbd27z":row[2], # 样品名称
                "numberField_lzxm9f8h":row[3], # 样品数量
                "textField_lyvp1czg":row[4], # 检测内容
                "textField_lyy54x9s":row[5], # 工程名称
                "textField_lqqbd27k":row[6], # 建设单位（委托单位
                "textField_lqqbd27m":row[7], # 施工单位
                "employeeField_lyxzlrkg":row[8], # 检测员
                "textField_lz6dgw9s":row[9], # 工程编号
                "dateField_lqqbd288":int(row[10].timestamp()*1000) if row[10] else None, # 委托日期
                "dateField_lqqbd29j":int(row[11].timestamp()*1000) if row[11] else None, # 报告日期
                "textField_lqqbd28n":row[12], # 委托备注
                "dateField_lzwcd0qm":int(row[13].timestamp()*1000) if row[13] else None, # 实际收样日期
                "selectField_lyy3k19t":row[14], # 工程区域
                "textField_lyy3k19u": area_map.get(row[14]) if row[14] else ""
            }
            create_result = yida_client.create_process_instance(
                "FORM-CA651D57089F42458AB9AA42162819E1EZ97",
                admin_user_id,
                commission_info,
                "TPROC--E9666S91CAWMCYUY90Z804C5UNJD2J9WCLQYL7"
            )
            pass
        

    def test_batch_update_commission(self):
        print("开始批量更新委托")
        for index in range(240589,241358):
            wtbh = f"ZJZJ/HJXY{index}"
            print(f"正在处理委托编号：{wtbh}")
            yida_client = YidaClient()
            result = yida_client.update_form_data_by_field(
                form_uuid='FORM-CA651D57089F42458AB9AA42162819E1EZ97',
                userId=admin_user_id,
                search_field=[
                                {
                                  "type": "TEXT",
                                  "operator": "eq",
                                  "componentName": "TextField",
                                  "key": "textField_lqqbd279",
                                  "value": wtbh
                                }
                              ],
                update_field={
                    "textField_lyvp1czg":'["总挥发性有机化合物TVOC","二甲苯","甲苯","氨","甲醛","苯","氡"]'
                }
            )
            if(result == "success"):
                # time.sleep(1)
                continue
            else:
                print(f"更新委托编号：{wtbh}失败")
                return
        print("批量更新委托完成")